package com.googlecode.imule.redundant;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;


/**
 * A class to server communication over UDP
 * @author Neil Cowzer
 * @author Mike Solomon
 */
public class UDPCommunication {

	// the packet to store the received information.
	private DatagramPacket infoPacket;
	
	// the outbound communication socket
	private DatagramSocket outSocket;
	
	// the inbound communication listener
	private CommThread listener;
	
	// TODO: remove
	private String username;
	private InetAddress address;
	private int port;
	
	
	/**
	 * Initialises a UDP communication stream
	 * @throws SocketException
	 */
	public UDPCommunication(String username) throws SocketException {
		this.username = username;
		
		DatagramSocket inSocket = new DatagramSocket();
		outSocket = new DatagramSocket();
		infoPacket = new DatagramPacket(new byte[4096], 4096);
		
		this.address = inSocket.getInetAddress();	// the ip to receive stuff on
		this.port = inSocket.getLocalPort();	// the port
		
		System.out.println(port);
		
		listener = new CommThread(inSocket, infoPacket);
		listener.start();
	}
	
	/**
	 * Takes string message and sends it through output socket
	 * @param message - string message
	 * @throws IOException
	 */
	public void Send(String message) throws IOException{
		String toSend = "[" + username + "]: " + message;
		byte[] toSendData = toSend.getBytes("ISO-8859-1");
		DatagramPacket thePacket = new DatagramPacket(toSendData, toSendData.length);
		
		// Cure
		thePacket.setAddress(InetAddress.getByName("127.0.0.1"));
		thePacket.setPort(port);
		outSocket.send(thePacket);
	}
	
	/**
	 * Used to set port per contact in list
	 * @param x - integer input
	 */
	public void setPort(int x){
		port = x;
	}
	
	/*
	 * Used to close socket after application closes
	 */
	public void closeOutSocket(){
		this.outSocket.close();
	}
	
	/**
	 * Used to set address of contact to send to
	 * @param a
	 * @throws UnknownHostException
	 */
	public void setAddress(String a) throws UnknownHostException{
		this.address = InetAddress.getByName(a);
	}
	
	/**
	 * Main Test method
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		UDPCommunication test = new UDPCommunication("one");
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("port:");
		int newPort = scanner.nextInt();
		test.setPort(newPort);
		
		String input = "";
		
		while(!input.equalsIgnoreCase("close")){
			input = scanner.nextLine();
			test.Send(input);
		}
		System.out.println("closing application");
		System.exit(0);
	}
}
